package serviceGoods

import (
	"context"
	"encoding/json"
	goods_pb "mxshop/api/goods/v1"
	"mxshop/app/mxshop_api/api/internal/data"
	dtoGoods "mxshop/app/mxshop_api/api/internal/domain/dto/goods"
	srvGoods "mxshop/app/mxshop_api/api/internal/service/goods"
	code2 "mxshop/gmicro/pkg/code"
	"mxshop/gmicro/pkg/errors"
)

type GoodsService struct {
	data data.DataFactory
}

func (gs *GoodsService) GoodsList(ctx context.Context, req *dtoGoods.GoodsFilter) (*dtoGoods.GoodDTOList, error) {
	var ret dtoGoods.GoodDTOList
	var doGoodsFilter goods_pb.GoodsFilterRequest

	byteReq, _ := json.Marshal(req)
	if err := json.Unmarshal(byteReq, &doGoodsFilter); err != nil {
		return nil, errors.WithCode(code2.ErrEncodingJSON, "编码 json数据 失败")
	}

	rsp, err := gs.data.Goods().Goods().List(ctx, &doGoodsFilter)
	if err != nil {
		return nil, errors.FromGrpcError(err)
	}

	for _, v := range rsp.Items {
		ret.Items = append(ret.Items, &dtoGoods.GoodsDTO{GoodDO: *v})
	}

	return &ret, nil
}

func (gs *GoodsService) BatchGetGoods(ctx context.Context, ids []int64) (*dtoGoods.GoodDTOList, error) {
	var ret dtoGoods.GoodDTOList

	rsp, err := gs.data.Goods().Goods().GetBatch(ctx, ids)
	if err != nil {
		return nil, errors.FromGrpcError(err)
	}

	for _, v := range rsp.Items {
		ret.Items = append(ret.Items, &dtoGoods.GoodsDTO{GoodDO: *v})
	}

	return &ret, nil
}

func (gs *GoodsService) GetGoodsDetail(ctx context.Context, id int64) (*dtoGoods.GoodsDTO, error) {
	var ret dtoGoods.GoodsDTO

	rsp, err := gs.data.Goods().Goods().Get(ctx, id)
	if err != nil {
		return nil, errors.FromGrpcError(err)
	}

	ret.GoodDO = *rsp

	return &ret, nil
}

func (gs *GoodsService) CreateGoods(ctx context.Context, req *dtoGoods.GoodsDTO) (*dtoGoods.GoodsDTO, error) {
	var ret dtoGoods.GoodsDTO

	rsp, err := gs.data.Goods().Goods().Create(ctx, &req.GoodDO)
	if err != nil {
		return nil, errors.FromGrpcError(err)
	}

	ret.Id = rsp.Id

	return &ret, nil
}

func (gs *GoodsService) UpdateGoods(ctx context.Context, req *dtoGoods.GoodsDTO) error {
	return gs.data.Goods().Goods().Update(ctx, &req.GoodDO)
}

func (gs *GoodsService) DeleteGoods(ctx context.Context, id int64) error {
	return gs.data.Goods().Goods().Delete(ctx, id)
}

func newGoods(data data.DataFactory) srvGoods.GoodsSrv {
	return &GoodsService{data: data}
}
